#include "zcpuinfo.h"

ZCpuInfo::ZCpuInfo(QObject *parent) : QObject(parent)
{
    QTimer *ptime(new QTimer);
    connect(ptime,&QTimer::timeout,[this](){this->get_cpu_usage__();});
    ptime->start(1000);
}

bool ZCpuInfo::get_cpu_usage__(int count)
{
    QProcess process;
    process.setArguments(QStringList("/proc/stat"));
    process.setProgram("cat");
    process.start();
    process.waitForFinished();
    QString str = process.readLine();
    str.replace("\n","");
    str.replace(QRegExp("( ){1,}")," ");
    auto lst = str.split(" ");
    if(lst.size() > 3)
    {
        double use = lst[1].toDouble() + lst[2].toDouble() + lst[3].toDouble();
        double total = 0;
        for(int i = 1;i < lst.size();++i)
            total += lst[i].toDouble();
        if(total - m_cpu_total__ > 0)
        {
            qDebug("cpu rate:%.2lf%%",(use - m_cpu_use__) / (total - m_cpu_total__) * 100.0);
            m_cpu_total__ = total;
            m_cpu_use__ = use;
            return true;
        }
    }
    return false;
}
